package com.macro.mall.portal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.macro.mall.mapper.ExExamPapperMapper;
import com.macro.mall.mapper.ExExamResultMapper;
import com.macro.mall.mapper.ExQuestionOptionMapper;
import com.macro.mall.mapper.ExQuestionsMapper;
import com.macro.mall.model.*;
import com.macro.mall.portal.domain.MemberDetails;
import com.macro.mall.portal.service.ExExamPapperService;
import com.macro.mall.portal.vo.ExExamAnswerVO;
import com.macro.mall.portal.vo.ExExamPapperSaveVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ExExamPapperServiceImpl implements ExExamPapperService {
    @Autowired
    private ExExamPapperMapper examPapperMapper;

    @Autowired
    private ExQuestionsMapper questionMapper;

    @Autowired
    private ExQuestionOptionMapper questionOptionMapper;

    @Autowired
    private ExExamResultMapper exExamResultMapper;


    @Override
    public ExExamPapper getById(Long id) throws Exception{
        ExExamPapper exExamPapper = examPapperMapper.selectByPrimaryKey(id);

        if (exExamPapper == null) {
            return new ExExamPapper();
        }
        //获取试题信息
        ExQuestionsExample questionExample = new ExQuestionsExample();
        ExQuestionsExample.Criteria questionCriteria = questionExample.createCriteria();
        questionCriteria.andExamIdEqualTo(exExamPapper.getId());
        questionExample.setOrderByClause(" seq asc ");
        List<ExQuestions> questionList = questionMapper.selectByExample(questionExample);
        if(questionList!=null && questionList.size()>0){
            ExQuestionOptionExample optionExample ;
            ExQuestionOptionExample.Criteria optionCriteria;
            for(ExQuestions question : questionList){
                question.setAnswer("");  //app不讲答案返回
                optionExample = new ExQuestionOptionExample();
                optionCriteria = optionExample.createCriteria();
                optionCriteria.andQuestionIdEqualTo(question.getId());
                optionExample.setOrderByClause(" seq asc ");
                List<ExQuestionOption> optionList = questionOptionMapper.selectByExample(optionExample);
                question.setOptionList(optionList);
            }
        }
        exExamPapper.setQuestionList(questionList);
        return exExamPapper;
    }

    public  JSONObject submitExam(ExExamPapperSaveVO examPapperVO) throws Exception{

        Long userId = null;
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
            userId = memberDetails.getUmsMember().getId();
        } catch (Exception e) {
            log.error("",e);
            userId = 0L;
        }
        if (userId==null ||userId==0) {
            throw new Exception("获取登录信息失败");
        }

        ExExamPapper exExamPapperDB = examPapperMapper.selectByPrimaryKey(examPapperVO.getExamId());
        if(exExamPapperDB == null || exExamPapperDB.getPassScore()==null ){
            throw new Exception(" 提交考试出错：考卷数据异常，请联系系统管理员 examId="+examPapperVO.getExamId());
        }
        float totalScore=0;
        ExQuestionsExample questionExample = new ExQuestionsExample();
        ExQuestionsExample.Criteria questionCriteria = questionExample.createCriteria();
        questionCriteria.andExamIdEqualTo(examPapperVO.getExamId());
        questionExample.setOrderByClause(" seq asc ");
        List<ExQuestions> questionList = questionMapper.selectByExample(questionExample);
        if(questionList!=null && questionList.size()>0){
            for(ExQuestions questionDB : questionList){
                 for(ExExamAnswerVO answer : examPapperVO.getAnswerList()){
                     if(questionDB.getId().intValue() == answer.getQuestId().intValue()){
                         if(questionDB.getAnswer().trim().equals(answer.getAnswer().trim())){
                             totalScore = totalScore+questionDB.getScore();
                         }
                         break;
                     }
                 }
            }
        }
        String isPass="N";
        if(totalScore>=exExamPapperDB.getPassScore()){
            isPass="Y";
        }

        ExExamResult  result = new ExExamResult();
        result.setExamId(exExamPapperDB.getId());
        result.setCollegeId(examPapperVO.getCollegeId());
        result.setTrainingId(examPapperVO.getTrainingId());
        result.setMemberId(Integer.valueOf(userId.toString()));
        result.setScore(totalScore);
        result.setIspass(isPass);
        result.setCreateTime(new Date());

        exExamResultMapper.insert(result);

        JSONObject resultJSON=new JSONObject();
        if("Y".equals(isPass)){
            resultJSON.put("isPass",isPass);
            resultJSON.put("desc","通过");
        }else{
            resultJSON.put("isPass",isPass);
            resultJSON.put("desc","未通过");
        }

        return resultJSON;
    }
    public List<Map<String,Object>> getCertificateList(Map<String,Object> paramMap)  throws Exception{

        Long userId = null;
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
            userId = memberDetails.getUmsMember().getId();
        } catch (Exception e) {
            log.error("",e);
            userId = 0L;
        }
        if (userId==null ||userId==0) {
            throw new Exception("获取登录信息失败");
        }
        paramMap.put("memberId",userId);
        List<Map<String,Object>> mapList =  exExamResultMapper.getCertificateList(paramMap);
        return mapList;
    }
    public String isPassByTrainingId(Integer trainingId) {
        String isPass="N";
        try {
            Long userId = this.getLoginUserId();
            isPass= this.isPassByUserIdAndTrainingId(trainingId, userId);
        }catch (Exception e){
            log.error("查询考试是否通过异常：trainingId="+trainingId+",错误信息："+e.getMessage());
            isPass= "N";
        }
        return isPass;
    }
    public String isPassByUserIdAndTrainingId(Integer trainingId,Long userId)  throws Exception{

        if (userId==null ||userId==0) {
            throw new Exception("获取登录信息失败");
        }

        ExExamResultExample examResultExample = new ExExamResultExample();
        ExExamResultExample.Criteria examResultCriteria = examResultExample.createCriteria();
        examResultCriteria.andTrainingIdEqualTo(trainingId);
        examResultCriteria.andMemberIdEqualTo(Integer.valueOf(userId.toString()));
        examResultCriteria.andIspassEqualTo("Y");
        long count =exExamResultMapper.countByExample(examResultExample);

        if(count>0){
            return "Y";
        }else{
            return "N";
        }
    }
    private  Long getLoginUserId(){
        Long userId = null;
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
            userId = memberDetails.getUmsMember().getId();
        } catch (Exception e) {
            log.error("",e);
            userId = 0L;
        }
        return userId;
    }
}